package fr.upmc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import fr.upmc.dao.ContactDAO;
import fr.upmc.utils.HibernateUtils;
import fr.upmc.utils.SessionTracker;


public class DeleteContact extends HttpServlet {

	private static final long serialVersionUID = -345334441605988923L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		//if user not connected, get him the hell out of here
		if(!SessionTracker.isUserConnected(request))
		{
			SessionTracker.redirectToHome(response);
		}
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		long id = - 1;
		
		try {
			id = Long.parseLong(request.getParameter("contactId"));
		} catch (Exception e) {
			out.print("error");
			return;
		}
		

		Session session = HibernateUtils.getSessionFactory().openSession();
		ContactDAO dao = new ContactDAO(session);

		if(dao.delete(id) == true){
			out.print("success");
		}
		else{
			//out.println("<h2>Contact " + id + " deja supprime !</h2>");
			out.print("success");
		}
		
		out.close();
		session.close();
		
		return;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		doGet(request,response);

		return;
	}
}
